import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

const instance = axios.create({
  baseURL: '/api',
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    console.log('Sending request:', config)
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    console.log('Received response:', response)
    return response
  },
  error => {
    console.error('Response error:', error)
    if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
      ElMessage.error('请求超时，请稍后重试')
    } else {
      const message = error.response?.data?.message || '请求失败'
      ElMessage.error(message)
    }
    
    if (error.response) {
      const status = error.response.status
      const message = error.response.data?.message || '未知错误'
      
      switch (status) {
        case 401:
          ElMessage.error(`未授权：${message}`)
          localStorage.clear()
          router.push('/login')
          break
        case 403:
          ElMessage.error(`无权限：${message}`)
          break
        case 404:
          ElMessage.error(`资源不存在：${message}`)
          break
        case 500:
          ElMessage.error(`服务器错误：${message}`)
          break
        default:
          ElMessage.error(message)
      }
    } else if (error.request) {
      ElMessage.error('网络错误，请检查您的网络连接')
    } else {
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

export default instance 